<template>
  <a-drawer :title="type === 0 ? '新增场次' : '编辑场次'" :width="500" :visible="visible" :body-style="{ paddingBottom: '80px' }" @close="onClose">
    <a-form :model="form" layout="vertical">
      <a-form-item label="标题： " name="title">
        <a-input v-model:value="form.title" placeholder="请输入场次标题" autocomplete="off" @change="change" />
      </a-form-item>

      <a-form-item label="状态： " name="status">
        <a-space size="middle">
          <a-select ref="formRef" v-model:value="form.status" style="width: 120px" placeholder="选择状态" @change="change">
            <a-select-option :value="0">未开始</a-select-option>
            <a-select-option :value="1">进行中</a-select-option>
            <a-select-option :value="2">已结束</a-select-option>
          </a-select>
          <a-button @click="openCheckoutModal">选择招新</a-button></a-space
        >
        <span style="padding-left: 10px">选择了：{{ chosRecruitmentTitle ? chosRecruitmentTitle : '未选择' }}</span>
      </a-form-item>

      <a-form-item label="日期： " name="date">
        <a-date-picker v-model:value="form.date" />
      </a-form-item>

      <a-form-item label="地点： " name="address">
        <a-input v-model:value="form.address" placeholder="请输入面试地点" autocomplete="off" @change="change" />
      </a-form-item>

      <a-form-item label="内容： " name="information">
        <a-textarea v-model:value="form.information" placeholder="请输入场次内容" auto-size @change="change" />
      </a-form-item>

      <a-form-item label="最大预约人数：" name="max">
        <a-input-number v-model:value="form.max" :min="1" :defaultValue="1" style="width: 100px" placeholder="请输入数字" />
      </a-form-item>
    </a-form>

    <a-row type="flex" justify="end">
      <a-space size="middle">
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="plusInterview" v-if="type === 0">添加</a-button>
        <a-button type="primary" @click="updateInterview()" v-if="type === 1">修改</a-button>
      </a-space>
    </a-row>
  </a-drawer>
  <choose-interview-event ref="RefChilde" @chosTitle="chosTitle" :chosTitle="chosTitle" />
</template>

<script lang="ts">
import { defineComponent, Ref, ref, toRaw, watch } from 'vue'
import { message } from 'ant-design-vue'
import ChooseInterviewEvent from '../../../../components/ChooseInterviewEvent.vue'
import { post, put, detele } from '../../../../utils/request/request'

interface FormState {
  interview_id: number | undefined
  title: string
  address: string
  information: string
  date: string
  max: number | undefined
  status: number | undefined
}

const form: Ref<FormState> = ref({
  interview_id: undefined,
  title: '', //标题
  address: '', //地点
  information: '', //信息
  date: '', //日期时间
  max: undefined, //最大人数
  status: 0 //状态，0.未开始、1.可预约、2.停止预约、3.可签到、4.停止签到
})

const deleteList: Ref<number[]> = ref([])

const isChange = ref<boolean>(false)

// 调用子组件方法，打开 modal
const useCheckoutEffect = () => {
  const RefChilde = ref()
  const chosRecruitmentTitle = ref<string>('')
  const openCheckoutModal = () => {
    RefChilde.value.showModal()
  }
  return { RefChilde, chosRecruitmentTitle, openCheckoutModal }
}

// 抽屉相关逻辑
const useDrawerEffect = () => {
  const visible = ref<boolean>(false)
  const showDrawer = () => {
    visible.value = true
  }
  const onClose = () => {
    visible.value = false
    form.value = {
      interview_id: undefined,
      title: '', //标题
      address: '', //地点
      information: '', //信息
      date: '', //日期时间
      max: undefined, //最大人数
      status: undefined //状态，0.未开始、1.可预约、2.停止预约、3.可签到、4.停止签到
    }
  }
  return { visible, showDrawer, onClose }
}

// 网络请求相关逻辑
const useHttpRequestEffect = (token: string, emit: any, visible: Ref<boolean>, form: Ref<FormState>) => {
  const postData = async () => {
    const postRes: any = await post('/admin/api/v1/recruitment/interview/batch', toRaw(form.value), token)
    console.log(postRes)
    if (postRes?.status_code === 0) {
      message.success('添加成功', 3)
      emit('getData')
      visible.value = false
    } else {
      message.error('添加失败', 3)
    }
  }
  const putData = async (id: number) => {
    if (id) {
      const putRes: any = await put(`/admin/api/v1/recruitment/interview/batch/${id}`, toRaw(form.value), token)
      if (putRes?.status_code === 0) {
        message.success('修改成功', 3)
        emit('getData')
        visible.value = false
      } else {
        message.error('修改失败', 3)
      }
    }
  }
  return { postData, putData }
}

// 表单相关逻辑
const useFormEffect = (token: string, emit: any, visible: Ref<boolean>, props: any) => {
  const propsId = ref<number>(1)
  watch(
    () => props.chosId,
    (newVal: number, oldVal: number) => {
      propsId.value = newVal
    }
  )
  const { postData, putData } = useHttpRequestEffect(token, emit, visible, form)
  const plusInterview = () => {
    if (form.value.interview_id && form.value.title && form.value.address && form.value.information && form.value.date && form.value.max) {
      postData()
      form.value = {
        interview_id: undefined,
        title: '', //标题
        address: '', //地点
        information: '', //信息
        date: '', //日期时间
        max: undefined, //最大人数
        status: 0 //状态，0.未开始、1.可预约、2.停止预约、3.可签到、4.停止签到
      }
    } else {
      message.warn('请填写完成后再提交')
    }
  }
  const updateInterview = () => {
    console.log(toRaw(form.value))
    if (isChange.value) {
      putData(propsId.value)
    } else {
      visible.value = false
      message.info('没有修改')
    }
  }
  return { propsId, plusInterview, updateInterview }
}

export default defineComponent({
  emits: ['getData'],
  props: ['chosId', 'type', 'form'],
  components: {
    ChooseInterviewEvent
  },
  setup(props, { emit }) {
    const token: string = localStorage.getItem('token') as string
    const { RefChilde, chosRecruitmentTitle, openCheckoutModal } = useCheckoutEffect()
    // 获得ChooseRecruitment子组件传值
    const chosTitle = (record: { id: number; title: string }) => {
      chosRecruitmentTitle.value = record.title
      form.value.interview_id = record.id
    }
    const { visible, showDrawer, onClose } = useDrawerEffect()
    const { propsId, plusInterview, updateInterview } = useFormEffect(token, emit, visible, props)
    watch(chosRecruitmentTitle, () => {
      isChange.value = true
    })
    const change = () => {
      isChange.value = true
    }

    watch(
      () => props.form,
      (newVal, oldVal) => {
        if (newVal) {
          form.value = newVal
        } else {
          form.value = {
            interview_id: undefined,
            title: '', //标题
            address: '', //地点
            information: '', //信息
            date: '', //日期时间
            max: undefined, //最大人数
            status: undefined //状态，0.未开始、1.可预约、2.停止预约、3.可签到、4.停止签到
          }
        }
      }
    )

    return {
      RefChilde,
      chosRecruitmentTitle,
      openCheckoutModal,
      form,
      visible,
      showDrawer,
      plusInterview,
      updateInterview,
      onClose,
      deleteList,
      chosTitle,
      propsId,
      change,
      isChange
    }
  }
})
</script>
